<template>
    <div class="container">
        <div class="addcompany">
            <div class="title">
                <div class="btn" @click="backHandler">
                    <el-icon :size="20" color="#FF6B00">
                        <ArrowLeftBold />
                    </el-icon>
                    <span>{{ type ? '返回' : '返回商户列表' }}</span>
                </div>
            </div>
            <div class="content">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                    <el-form-item label="企业名称" prop="merchantName">
                        <el-input
                            v-model.trim="form.merchantName"
                            maxlength="50"
                            show-word-limit
                            :disabled="form.totalDisabled"
                            placeholder="请输入企业名称" />
                    </el-form-item>
                    <el-form-item label="企业代码" prop="regNo">
                        <el-input
                            v-model.trim="form.regNo"
                            maxlength="50"
                            show-word-limit
                            :disabled="form.totalDisabled"
                            placeholder="请输入请输入统一社会信用代码 / 组织机构代码 / 营业执照注册号" />
                    </el-form-item>
                    <el-form-item label="商城名称" prop="tenantName">
                        <el-input
                            v-model.trim="form.tenantName"
                            maxlength="30"
                            show-word-limit
                            :disabled="form.totalDisabled && form.specialDisabled"
                            placeholder="请输入商城名称" />
                    </el-form-item>
                    <el-form-item label="经营类目" prop="categoriesFirst">
                        <Categories
                            :cateList="form.cateList"
                            @selectCategories="selectCategories"
                            :disabled="form.totalDisabled"></Categories>
                    </el-form-item>
                    <el-form-item label="联系人姓名" prop="contactName">
                        <el-input
                            v-model.trim="form.contactName"
                            maxlength="30"
                            show-word-limit
                            :disabled="form.totalDisabled && form.specialDisabled"
                            placeholder="请输入联系人姓名" />
                    </el-form-item>
                    <el-form-item label="联系人手机" prop="contactMobile">
                        <el-input
                            v-model.trim="form.contactMobile"
                            :disabled="form.totalDisabled && form.specialDisabled"
                            placeholder="请输入联系人手机" />
                    </el-form-item>
                    <el-form-item label="商城简介" prop="tenantDesc">
                        <el-input
                            maxlength="200"
                            v-model.trim="form.tenantDesc"
                            type="textarea"
                            placeholder="请输入商城简介"
                            :autosize="{ minRows: 2 }"
                            resize="none"
                            :disabled="form.totalDisabled && form.specialDisabled"
                            show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item label="商城LOGO" prop="logo" :error="uploadErrMsg">
                        <ImgUpload :url="form.logo" @change="v => onUploadChange(v)" />
                    </el-form-item>
                </el-form>
                <div class="btnWrapper">
                    <el-button v-if="queryId" type="primary" class="btn" @click="addHandler">重新提交</el-button>
                    <el-button v-else type="primary" class="btn" @click="addHandler">
                        {{ type ? '编辑商户' : '创建商户' }}
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, inject, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import storage from '@/commons/storage';
import request from '@/request';
import Categories from './categories.vue';
import ImgUpload from './ImgUpload.vue';
import { isNotEmpty, isMobile } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();
const queryStatus = route.query.status;
const queryId = route.query.id;

const form = reactive({
    merchantName: '',
    regNo: '',
    tenantName: '',
    categoriesFirst: '',
    contactName: '',
    contactMobile: '',
    logo: '',
    tenantDesc: '',
    totalDisabled: false,
    specialDisabled: false,
    cateList: []
});
let formRef = ref(null);
let type = ref(false);
let selectedCategories = reactive([]);
let uploadErrMsg = ref('');

/**
 * 校验手机号
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */
const validatePhone = (rule, value, callback) => {
    if (isMobile(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的手机号!'));
    }
};

const rules = reactive({
    merchantName: [
        { required: true, message: '请输入企业名称', trigger: 'blur' },
        { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
    ],
    regNo: [
        { required: true, message: '请输入请输入统一社会信用代码 / 组织机构代码 / 营业执照注册号', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9]+$/, message: '企业代码格式不正确', trigger: 'blur' }
    ],
    tenantName: [
        { required: true, message: '请输入商城名称', trigger: 'blur' },
        { max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
    ],
    categoriesFirst: [{ required: true, message: '请选择经营类目', trigger: 'blur' }],
    contactName: [
        { required: true, message: '请输入联系人姓名', trigger: 'blur' },
        { max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
    ],
    contactMobile: [
        { required: true, message: '请输入联系人手机', trigger: 'blur' },
        { validator: validatePhone, trigger: 'blur' }
    ],
    tenantDesc: [{ required: true, message: '请输入商城简介', trigger: 'blur' }],
    logo: [{ required: true, message: '请上传商城LOGO', trigger: 'blur' }]
});

const onUploadChange = v => {
    form.logo = v;
    formRef.value.validateField('logo');
};

// 经营类目
const selectCategories = arr => {
    if (arr.length === 0) {
        form.categoriesFirst = '';
    } else {
        selectedCategories.length = 0;
        arr.map(item => {
            selectedCategories.push(item);
        });
        form.categoriesFirst = 'complete';
        formRef.value.validateField('categoriesFirst');
    }
};

const validatorFile = file => {
    const checkSize = new Promise(function (resolve, reject) {
        let _URL = window.URL || window.webkitURL;
        let image = new Image();
        image.onload = function () {
            resolve();
        };
        image.src = _URL.createObjectURL(file);
    }).then(
        () => {
            return true;
        },
        () => {
            uploadErrMsg.value = '上传图片尺寸限制1:1';
            return Promise.reject();
        }
    );
    return checkSize;
};

const logChangeHandler = obj => {
    form.logo = obj.imgUrl || '';
    uploadErrMsg.value = obj.msg || '';
};

/**
 * 新增企业商户
 */
const addHandler = () => {
    formRef.value.validate(async valid => {
        if (valid) {
            if (type.value || queryId) {
                await request('tenantUpdate', {
                    status: queryId ? 3 : 1,
                    regNo: form.regNo,
                    merchantName: form.merchantName,
                    tenantName: form.tenantName,
                    cateList: selectedCategories.map(item => {
                        return {
                            categoriesFirst: item.categoriesFirst,
                            categoriesSecond: item.categoriesSecond,
                            categoriesFirstName: item.categoriesFirstName,
                            categoriesSecondName: item.categoriesSecondName
                        };
                    }),
                    tenantDesc: form.tenantDesc,
                    contactMobile: form.contactMobile,
                    contactName: form.contactName,
                    logo: form.logo
                });
            } else {
                const res = await request('saveTenantServ', {
                    status: 3,
                    regNo: form.regNo,
                    merchantName: form.merchantName,
                    tenantName: form.tenantName,
                    cateList: selectedCategories.map(item => {
                        return {
                            categoriesFirst: item.categoriesFirst,
                            categoriesSecond: item.categoriesSecond,
                            categoriesFirstName: item.categoriesFirstName,
                            categoriesSecondName: item.categoriesSecondName
                        };
                    }),
                    tenantDesc: form.tenantDesc,
                    contactMobile: form.contactMobile,
                    contactName: form.contactName,
                    logo: form.logo
                });
            }
            const message = type.value
                ? '编辑成功'
                : queryId
                ? '提交成功！请耐心等待管理员审核'
                : '创建成功！请耐心等待管理员审核';
            ElMessage.success(message);
            router.back();
        }
    });
};

/**
 * 返回上一页
 */
const backHandler = () => {
    router.back();
};

// 反显数据
onMounted(async () => {
    if (queryStatus) {
        type.value = true;
        if (['3', '2'].includes(queryStatus)) {
            form.totalDisabled = true;
            form.specialDisabled = false;
        }
        const { data } = await request('tenantInfo', {
            tenantId: storage.get('ZW-TENANT-ID')
        });
        Object.assign(form, data);
        selectCategories(
            form.cateList.map(item => {
                return {
                    categoriesFirst: item.categoriesFirstCode,
                    categoriesFirstName: item.categoriesFirstName,
                    categoriesSecond: item.categoriesSecondCode,
                    categoriesSecondName: item.categoriesSecondName
                };
            })
        );
    }
    if (queryId) {
        storage.set('ZW-TENANT-ID', queryId);
        const { data } = await request('tenantInfo', {
            tenantId: queryId
        });
        Object.assign(form, data);
        selectCategories(
            form.cateList.map(item => {
                return {
                    categoriesFirst: item.categoriesFirstCode,
                    categoriesFirstName: item.categoriesFirstName,
                    categoriesSecond: item.categoriesSecondCode,
                    categoriesSecondName: item.categoriesSecondName
                };
            })
        );
    }
});
</script>
<style lang="scss" src="./style.scss" scoped></style>
